﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using WebApplicationFileSys.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Ajax.Utilities;
namespace WebApplicationFileSys.Controllers
{
    /// <summary>
    /// 登录，处理
    /// </summary>
    /// 添加时间：2023-8-31 17:44:08，
    public class LoginHandleController : Controller
    {
        private readonly static List<Claim> _administrator = new List<Claim>() {
             new Claim(ClaimTypes.Role,"admin"),
             new Claim(ClaimTypes.Role,"user"),
        };

        /// <summary>
        /// 普通用户权限配置
        /// </summary>
        private readonly static List<Claim> _user = new List<Claim>() {
             new Claim(ClaimTypes.Role,"user"),
        };
        //视图，登录
        public ActionResult LoginView()
        {
            return View();
        }

        //退出登录
        public ActionResult ExitLogin()
        {
            Session.Remove(KeyValueConfig.KeyUserSession);
            var cookie = new HttpCookie(KeyValueConfig.Cookie_Token);
            cookie.Expires = DateTime.Now.AddDays(-1); // 设置过期时间为过去的时间
            Response.Cookies.Add(cookie);
            return Redirect("/Home/Index");
        }


        //处理登录，
        public ActionResult DoLogin(string account, string pwd)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                return Json(new Result("账号不可为空"));
            }
            if (string.IsNullOrWhiteSpace(pwd))
            {
                return Json(new Result("密码不可为空"));
            }

            var users = SF.db.Login.FirstOrDefault(d => d.username == account);

            if (users != null)
            {
                string storedPassword = users?.password;
                if (pwd.Trim().Equals(storedPassword))
                {
                    Session[KeyValueConfig.KeyUserSession] = account;
                    string role = users.role;
                    bool ce = role.Equals("admin");
                    role = users?.LV + "";


                    var credentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KeyValueConfig.TokeKey)), SecurityAlgorithms.HmacSha256);
                    var claims = new List<Claim>();

                    claims = ce ? _administrator : _user;//管理权限

                    claims.Add(new Claim(ClaimTypes.Name, account));
                    claims.Add(new Claim(ClaimTypes.Name, role));

                    var token = new JwtSecurityToken(
                        issuer: KeyValueConfig.issuer,
                        audience: KeyValueConfig.audience,
                        claims: claims,
                        expires: DateTime.UtcNow.AddHours(48),
                        signingCredentials: credentials
                    );
                    var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                    var cookie = new HttpCookie(KeyValueConfig.Cookie_Token, jwtToken);

                    // 设置Cookie的过期时间
                    cookie.Expires = DateTime.Now.AddDays(7); // 设置为7天后过期

                    // 将Cookie添加到响应中
                    Response.Cookies.Add(cookie);



                    return Json(new Result(jwtToken, 1));
                }
                else
                {
                    return Json(new Result("密码错误"));
                }
            }
            // 创建JWT

            return Json(new Result("未知用户"));

        }

        public ActionResult DoRegister(string account, string pwd)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                return Json(new Result("账号不可为空"));
            }
            if (string.IsNullOrWhiteSpace(pwd))
            {
                return Json(new Result("密码不可为空"));
            }
            if (account.Length >= 6 || pwd.Length >= 6)
            {
                return Json(new Result("长度请勿大于6位"));
            }
            try
            {

                var users = SF.db.Login.FirstOrDefault(d => d.username == account);

                if (users != null)
                {
                    return Json(new Result("账号已存在"));
                }

                Login NewUser = new Login()
                {
                    username = account,
                    password = pwd,
                    role = "user",
                    LV = 1
                };
                SF.db.Login.Add(NewUser);
                SF.db.SaveChanges();

            }
            catch (Exception e)
            {
                return Json(new Result("注册异常:" + e.Message));
                throw;
            }

            return Json(new Result("注册成功", 1));
        }

    }
}